//
//  NBOAuthViewController.swift
//  NBSinaWeibo
//
//  Created by ac on 16/5/22.
//  Copyright © 2016年 ac. All rights reserved.
//

import UIKit
import SVProgressHUD

class NBOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadWebView()
        setNavBtn()
    }
    
    @objc private func backToLastVC() -> () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func textAccount(){
        let jsStr = "document.getElementById('userId').value = '865770853@qq.com',document.getElementById('passwd').value = 'bugaosuNI412.'"
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
    func setNavBtn() -> () {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(backToLastVC))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", target: self, action: #selector(textAccount))
    }
    
    func loadWebView() -> () {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let URL = NSURL(string: urlString)
        let req = NSURLRequest(URL: URL!)
        webView.loadRequest(req)
    }

    override func loadView() {
        view = webView
        webView.opaque = false
        webView.backgroundColor = UIColor.whiteColor()
        webView.delegate = self
    }
    
}

extension NBOAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        let reqStr = request.URL?.absoluteString ?? ""
        let codeStr = "code="
        
        if reqStr.containsString(codeStr) {
            
            let code = reqStr.substringFromIndex((reqStr.rangeOfString(codeStr)?.endIndex)!)
            
            NBUserAccountViewModel.sharedViewModel.loadAccessToken(code, finish: { (isSuccess) in
                if isSuccess {
                    NSNotificationCenter.defaultCenter().postNotificationName(changeKeyWindowView, object: nil)
                }else{
                    SVProgressHUD.showErrorWithStatus(errorAlert)
                    return
                }
                
            })
            
            
            return false
        }
        
        
        
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
        
    }
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
}
